import { ActionContext, Store } from "vuex";

export interface Product {
  id: number;
  name: string;
  unitPrice: number;
}

export interface ProductInBasket {
  product: Product;
  isSelected: boolean;
}

export interface BasketState {
  items: ProductInBasket[];
  totalAmount: number;
}

type BasketContext = ActionContext<BasketState, BasketState>;

export default {
  namespaced: false,

  state: {
    items: [],
    totalAmount: 0
  },

  getters: {
    getProductNames(state: BasketState) {
      return state.items.map(item => item.product.name);
    },
    getTotalAmountWithoutDiscount(state: BasketState) {
      return state.items.reduce(
        (total, item) => total + item.product.unitPrice,
        0
      );
    }
  },

  mutations: {
    appendItem(
      state: BasketState,
      item: { product: Product; atTheEnd: boolean }
    ) {
      state.items.push({ product: item.product, isSelected: false });
    },
    setTotalAmount(state: BasketState, totalAmount: number) {
      state.totalAmount = totalAmount;
    }
  },

  actions: {
    // async updateTotalAmount(context: BasketContext, discount: number): Promise<void> {
    //     const totalBeforeDiscount = readTotalAmountWithoutDiscount(context);
    //     const response = await axios.get(`/api/calculatetotal/${totalBeforeDiscount}/${discount}`);
    //     commitSetTotalAmount(context, response.data.totalAfterDiscount);
    // },
  }
};

// export const createStore = () => new Store<BasketState>(basket);

// const { commit, read, dispatch } =
//      getStoreAccessors<BasketState, BasketState>(""); // We pass namespace here, if we make the module namespaced: true.

// export const readProductNames = read(basket.getters.getProductNames);
// export const readTotalAmountWithoutDiscount = read(basket.getters.getTotalAmountWithoutDiscount);
// export const dispatchUpdateTotalAmount = dispatch(basket.actions.updateTotalAmount);
// export const commitAppendItem = commit(basket.mutations.appendItem);
// export const commitSetTotalAmount = commit(basket.mutations.setTotalAmount);
